package com.liflag.music.util;


import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * @author dafeiyu
 * @date Created in 2021/6/25,0025.
 */

public class KuwoUtil {

    /**
     * 搜索歌曲
     * @param key
     * @param n  第几页
     * @return
     * @throws Exception
     */
    public com.alibaba.fastjson.JSONObject search(String key,int n) throws Exception{
        StringBuilder result = new StringBuilder();
        int random = RandomUtil.randomInt(10000000, 99999999);
        BufferedReader in = null;
        String keyParam = URLEncoder.encode(key,"utf-8");
        String urlNameString = "http://bd.kuwo.cn/api/www/search/searchMusicBykeyWord?key="+keyParam+"&pn="+n+"&rn=50";
        URL realUrl = new URL(urlNameString);
        URLConnection connection = realUrl.openConnection();
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("csrf", random+"");
        connection.setRequestProperty("Referer", "http://bd.kuwo.cn");
        connection.setRequestProperty("Cookie", "kw_token="+random);
        connection.connect();
        in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
        String line;
        while ((line = in.readLine()) != null){
            result.append(line);
        }
        in.close();
        return JSONObject.parseObject(result.toString());
    }

    //获取歌曲详情
    //  http://wapi.kuwo.cn/api/www/music/musicInfo?mid=228908
    public JSONObject getMusicInfo(String mid) throws Exception{
        String urlString = "http://wapi.kuwo.cn/api/www/music/musicInfo";
        String result = HttpUtils.sendGet(urlString,"mid="+mid);
        return JSONObject.parseObject(result);
    }

    //获取歌曲跳转url
    // https://bd.kuwo.cn/url?rid=71368021&type=convert_url3&br=128kmp3
    public static JSONObject getMusicUrl(String mid) throws Exception{
        JSONObject jsonObject = null;
        URL url = new URL("https://bd.kuwo.cn/url?rid=" + mid + "&type=convert_url3&br=320kmp3");
        BufferedReader r;
        try {
            r = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
            jsonObject = JSON.parseObject(r.readLine());
        } catch (Exception e) {
            url = new URL("https://bd.kuwo.cn/url?rid=" + mid + "&type=convert_url3&br=128kmp3");
            r = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
            try {
                jsonObject = JSON.parseObject(r.readLine());
            } catch (Exception x) {
                url = new URL("https://bd.kuwo.cn/url?rid=" + mid + "&type=convert_url3&br=128kmp3&from=web&response=url&format=mp3");
                r = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
                jsonObject = JSON.parseObject(r.readLine());
            }
        }
        return jsonObject;
    }

    //获取歌曲跳转url
    //备用地址 http://m.kuwo.cn/newh5app/api/mobile/v1/music/src/94237
    //https://antiserver.kuwo.cn/anti.s?type=convert_url&rid=325842&format=mp3&response=url&qq-pf-to=pcqq.group
    public static JSONObject getMusicUrl2(String mid) throws Exception{
        JSONObject jsonObject = new JSONObject();
        URL url = new URL("http://antiserver.kuwo.cn/anti.s?type=convert_url&rid=" + mid + "&format=aac|mp3&response=url");
        BufferedReader r = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
        String acc = r.readLine();
        jsonObject.put("url",acc);
        return jsonObject;
    }

    //获取歌歌词
    // https://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId=228908
    public static JSONObject getLrc(String mid) throws Exception{
        String urlString = "http://m.kuwo.cn/newh5/singles/songinfoandlrc";
        String result =HttpUtils.sendGet(urlString,"musicId="+mid);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getJSONObject("data");
    }

    public static String getres(String key,String page)  {
        key=key.replace(" ","&nbsp");
        String randomString= RandomUtil.randomNumbers(8);
        String url = "http://bd.kuwo.cn/api/www/search/searchMusicBykeyWord?key="+key+"&pn="+page+"&rn=30";
        HttpGet get = new HttpGet(url);
        get.addHeader("Referer","http://bd.kuwo.cn");
        get.addHeader("csrf",randomString);
        get.addHeader("Cookie","kw_token="+randomString);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        String s="";
        try {
            response = client.execute(get);
            HttpEntity entity = response.getEntity();
            s = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s.replace("&nbsp"," ");
    }
    public static String getLRC(String key)  {
        String url = "http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId="+key;
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        get.addHeader("Referer","http://bd.kuwo.cn");
        String randomString= RandomUtil.randomNumbers(8);
        get.addHeader("csrf",randomString);
        get.addHeader("Cookie","kw_token="+randomString);
        CloseableHttpResponse response = null;
        String s="";
        try {
            response = client.execute(get);
            HttpEntity entity = response.getEntity();
            s = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        s=s.replace("&nbsp"," ");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", JSON.parseObject(s).getJSONObject("data").getJSONArray("lrclist"));
        jsonObject.put("code",200);
        jsonObject.put("msg","获取成功");
        return jsonObject.toJSONString();
    }

}
